const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const { riddleModel, postModel, pingjiaModel ,shishouModel,newsModel, quizModel, quizRecordModel, bencaoQuizModel, bencaoQuizRecordModel } = require('../model/model');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const fsPromises = require('fs').promises;
const sharp = require('sharp');
// const rateLimit = require('express-rate-limit');
const WebSocket = require('ws');
const { spawn } = require('child_process');


// 获取所有谜语（可分页）
router.get('/riddle', async (req, res) => {
  try {
    const { page = 1, limit = 10, difficulty } = req.query;
    const query = {};

    // 难度筛选
    if (difficulty) query.difficulty = parseInt(difficulty);

    // 分页查询
    const [riddles, total] = await Promise.all([
      riddleModel.find(query)
        .skip((page - 1) * limit)
        .limit(parseInt(limit))
        .sort({ _id: -1 }),
      riddleModel.countDocuments(query)
    ]);

    res.json({
      code: 200,
      message: '获取成功',
      data: {
        list: riddles,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 随机获取多个谜语（前端需要）
router.get('/riddle/random', async (req, res) => {
  try {
    const count = parseInt(req.query.count) || 6; // 默认返回6个

    // 使用aggregate实现真正随机
    const randomRiddles = await riddleModel.aggregate([
      { $sample: { size: count } }
    ]);

    if (randomRiddles.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '没有找到谜语',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '获取成功',
      data: randomRiddles
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 获取单个谜语详情
router.get('/riddle/:id', async (req, res) => {
  try {
    if (!mongoose.Types.ObjectId.isValid(req.params.id)) {
      return res.status(400).json({
        code: 400,
        message: '无效的ID格式',
        data: null
      });
    }

    const riddle = await riddleModel.findById(req.params.id);
    if (!riddle) {
      return res.status(404).json({
        code: 404,
        message: '谜语不存在',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '获取成功',
      data: riddle
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 获取随机题目接口
router.get('/quiz/random', async (req, res) => {
  try {
    const count = parseInt(req.query.count) || 5; // 默认5题
    
    // 随机获取题目
    const questions = await quizModel.aggregate([
      { $sample: { size: count } }
    ]);
    
    if (questions.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '暂无题目',
        data: null
      });
    }
    
    // 移除正确答案和解析，只返回题目和选项
    const questionsForUser = questions.map(q => ({
      _id: q._id,
      title: q.title,
      question: q.question,
      options: q.options,
      category: q.category,
      difficulty: q.difficulty
    }));
    
    res.json({
      code: 200,
      message: '获取题目成功',
      data: questionsForUser
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 提交答案并获取结果
router.post('/quiz/submit', async (req, res) => {
  try {
    const { userId, answers, timeSpent } = req.body;
    
    if (!answers || !Array.isArray(answers)) {
      return res.status(400).json({
        code: 400,
        message: '答案格式错误',
        data: null
      });
    }
    
    // 获取题目详情
    const questionIds = answers.map(a => a.questionId);
    const questions = await quizModel.find({ _id: { $in: questionIds } });
    
    // 计算得分
    let correctCount = 0;
    const results = [];
    const userAnswers = [];
    const correctAnswers = [];
    
    for (let i = 0; i < answers.length; i++) {
      const userAnswer = answers[i];
      const question = questions.find(q => q._id.toString() === userAnswer.questionId);
      
      if (question) {
        const isCorrect = userAnswer.answer === question.correctAnswer;
        if (isCorrect) correctCount++;
        
        userAnswers.push(userAnswer.answer);
        correctAnswers.push(question.correctAnswer);
        
        results.push({
          questionId: question._id,
          question: question.question,
          options: question.options,
          userAnswer: userAnswer.answer,
          correctAnswer: question.correctAnswer,
          isCorrect,
          explanation: question.explanation
        });
      }
    }
    
    const score = Math.round((correctCount / answers.length) * 10); // 10分制
    
    // 保存答题记录
    const record = new quizRecordModel({
      userId: userId || 'anonymous',
      quizIds: questionIds,
      userAnswers,
      correctAnswers,
      score,
      totalQuestions: answers.length,
      timeSpent: timeSpent || 0
    });
    
    await record.save();
    
    res.json({
      code: 200,
      message: '提交成功',
      data: {
        score,
        correctCount,
        totalQuestions: answers.length,
        timeSpent,
        results
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 获取单题详情（用于查看解析）
router.get('/quiz/:id', async (req, res) => {
  try {
    const question = await quizModel.findById(req.params.id);
    
    if (!question) {
      return res.status(404).json({
        code: 404,
        message: '题目不存在',
        data: null
      });
    }
    
    res.json({
      code: 200,
      message: '获取成功',
      data: question
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 获取用户答题历史
router.get('/quiz/history/:userId', async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    
    const [records, total] = await Promise.all([
      quizRecordModel.find({ userId: req.params.userId })
        .sort({ completedAt: -1 })
        .skip((page - 1) * limit)
        .limit(parseInt(limit)),
      quizRecordModel.countDocuments({ userId: req.params.userId })
    ]);
    
    res.json({
      code: 200,
      message: '获取成功',
      data: {
        list: records,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});



// AI
// 创建一个函数来设置 WebSocket 服务器
function setupWebSocket(server) {
  const wss = new WebSocket.Server({ server });

  wss.on('connection', (ws) => {
    console.log('Client connected');

    ws.on('message', (message) => {
      console.log('Received:', message.toString());

      // 启动 Ollama 进程
      const ollama = spawn('ollama', ['run', 'deepseek-r1:8b'], {
        stdio: ['pipe', 'pipe', 'pipe'],
      });

      let responseData = '';

      // 监听 Ollama stdout 数据
      ollama.stdout.on('data', (data) => {
        responseData += data.toString();
        ws.send(data.toString()); // 逐步发送 AI 响应
      });

      // 监听 Ollama stderr 数据
      ollama.stderr.on('data', (data) => {
        console.error(`Ollama Error: ${data}`);
      });

      // Ollama 进程结束时发送关闭标志
      ollama.on('close', (code) => {
        console.log(`Ollama exited with code ${code}`);
        ws.send('[DONE]'); // 发送结束标识
      });

      // 向 Ollama 进程输入用户消息
      ollama.stdin.write(`${message}\n`);
      ollama.stdin.end();
    });

    ws.on('close', () => {
      console.log('Client disconnected');
    });
  });
}

// 确保上传目录存在 - 在服务器启动时执行
const uploadBaseDir = path.join(__dirname, '../uploads');
fsPromises.mkdir(uploadBaseDir, { recursive: true })
  .then(() => console.log(`上传目录已准备就绪: ${uploadBaseDir}`))
  .catch(err => {
    console.error("初始化上传目录失败:", err);
    // 如果目录无法创建，服务器可能无法正常工作，可以选择退出进程
    // process.exit(1); 
  });
// 合并分片文件
const mergeChunks = async (filename, totalChunks) => {
  const outputPath = path.join(uploadBaseDir, filename);

  return new Promise(async (resolve, reject) => {
    let writeStream = null;

    try {
      // 先检查所有分片是否存在
      const missingChunks = [];
      const chunkSizes = [];

      console.log(`开始检查 ${totalChunks} 个分片文件...`);

      for (let i = 0; i < totalChunks; i++) {
        const chunkPath = path.join(uploadBaseDir, `${filename}_${i}`);
        try {
          const stats = await fsPromises.stat(chunkPath);
          chunkSizes.push(stats.size);
          console.log(`分片 ${i}: ${stats.size} bytes`);
        } catch (err) {
          missingChunks.push(i);
          console.error(`分片文件不存在: ${chunkPath}`, err.message);
        }
      }

      if (missingChunks.length > 0) {
        throw new Error(`缺少分片: ${missingChunks.join(', ')}`);
      }

      // const totalSize = chunkSizes.reduce((sum, size) => sum + size, 0);
      // 创建写入流
      writeStream = fs.createWriteStream(outputPath);

      // 设置写入流错误处理
      writeStream.on('error', (error) => {
        console.error('写入流错误:', error);
        reject(error);
      });

      // 逐个合并分片
      for (let i = 0; i < totalChunks; i++) {
        const chunkPath = path.join(uploadBaseDir, `${filename}_${i}`);

        try {
          // 读取分片数据
          const chunkData = await fsPromises.readFile(chunkPath);

          // 写入合并文件
          await new Promise((resolveWrite, rejectWrite) => {
            writeStream.write(chunkData, (error) => {
              if (error) {
                console.error(`写入分片 ${i} 失败:`, error);
                rejectWrite(error);
              } else {
                resolveWrite();
              }
            });
          });

          console.log(`分片 ${i} 合并完成`);

          // 立即删除已处理的分片以释放磁盘空间
          try {
            await fsPromises.unlink(chunkPath);
            console.log(`分片 ${i} 已删除`);
          } catch (unlinkError) {
            console.warn(`删除分片文件失败: ${chunkPath}`, unlinkError.message);
          }

        } catch (chunkError) {
          console.error(`处理分片 ${i} 失败:`, chunkError);
          throw chunkError;
        }
      }

      // 关闭写入流
      writeStream.end();

      // 等待写入完成
      writeStream.on('finish', () => {
        console.log(`文件合并完成: ${outputPath}`);
        resolve(outputPath);
      });

    } catch (err) {
      console.error(`合并分片文件失败 (${filename}):`, {
        error: err.message,
        stack: err.stack,
        totalChunks,
        outputPath
      });
      // 清理资源
      if (writeStream) {
        writeStream.destroy();
      }

      // 尝试删除可能创建的不完整文件
      try {
        await fsPromises.unlink(outputPath);
        console.log('已删除不完整的合并文件');
      } catch (cleanupError) {
        console.warn('清理不完整文件失败:', cleanupError.message);
      }

      reject(err);
    }
  });
};

// 压缩图片或直接返回文件名（用于视频）
const processFile = async (filePath, originalFilename, mimetype) => {
  if (mimetype.startsWith('image/')) {
    const compressedName = `compressed_${originalFilename}`;
    const compressedPath = path.join(uploadBaseDir, compressedName);
    try {
      await sharp(filePath)
        .resize(1200, 1200, { fit: 'inside', withoutEnlargement: true })
        .jpeg({ quality: 80 })
        .toFile(compressedPath);

      try {
        await fsPromises.unlink(filePath); // 删除原始文件
      } catch (unlinkError) {
        console.error(`删除原始合并文件失败 ${filePath}:`, unlinkError.message);
      }
      return compressedName;
    } catch (error) {
      console.error('图片压缩失败:', error);
      throw error;
    }
  } else if (mimetype.startsWith('video/')) {
    // 对于视频文件，不进行压缩，直接返回原始文件名
    // 如果将来需要视频处理，可以在这里添加 ffmpeg 等逻辑
    return originalFilename;
  } else {
    // 对于其他不支持的文件类型，直接返回原始文件名（或者抛出错误）
    console.warn(`不支持的文件类型 ${mimetype}，直接返回原始文件名。`);
    return originalFilename;
  }
};

// 配置 multer 存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadBaseDir);
  },
  filename: function (req, file, cb) {
    // 从请求参数中获取原始文件名和分片索引
    const originalName = req.query.originalName ? decodeURIComponent(req.query.originalName) : null;
    const chunkIndex = req.query.chunkIndex;
    // const fileId = req.query.fileId ? decodeURIComponent(req.query.fileId) : null;

    if (!originalName || chunkIndex === undefined) {
      console.error('multer filename: 缺少必要信息 (originalName, chunkIndex)');
      return cb(new Error('文件名或分片索引信息缺失'));
    }

    // 确保文件名安全，移除可能导致路径问题的字符
    const safeOriginalName = originalName.replace(/[\/:*?"<>|]/g, '_');
    const filename = `${safeOriginalName}_${chunkIndex}`;
    console.log(`multer 生成文件名: ${filename}`);
    cb(null, filename);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 50 * 1024 * 1024 }, // 适当调高分片文件大小限制，视频可能更大，例如50MB
  fileFilter: (req, file, cb) => {
    const allowedTypes = [
      'image/jpeg', 'image/png', 'image/webp', 'image/jpg',
      'video/mp4', 'video/quicktime', 'video/webm', 'video/x-msvideo' // 允许视频 (MP4, MOV, WebM, AVI)
    ];
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error(`只允许上传图片和视频文件 (JPEG, PNG, WebP, MP4, MOV, WebM, AVI)。当前文件类型: ${file.mimetype}`));
    }
  }
});

// 获取最终文件名接口
router.get('/upload/final/:fileId', async (req, res) => {
  try {
    const fileId = decodeURIComponent(req.params.fileId);

    // 从fileId中提取原始文件名
    // fileId格式: 原始文件名_随机数_时间戳
    const parts = fileId.split('_');
    if (parts.length < 3) {
      return res.status(400).json({
        code: 400,
        message: '无效的文件ID格式'
      });
    }

    // 重新组合原始文件名（去掉最后两个部分：随机数和时间戳）
    const originalName = parts.slice(0, -2).join('_');
    const safeOriginalName = originalName.replace(/[\/:*?"<>|]/g, '_');

    // 检查文件是否存在于uploads目录
    const possibleFiles = [
      safeOriginalName, // 原始文件名
      `compressed_${safeOriginalName}` // 压缩后的文件名
    ];

    for (const filename of possibleFiles) {
      const filePath = path.join(uploadBaseDir, filename);
      try {
        await fsPromises.access(filePath);
        console.log(`找到文件: ${filename}`);
        return res.json({
          code: 200,
          message: '获取文件名成功',
          data: { filename }
        });
      } catch (err) {
        // 文件不存在，继续检查下一个
      }
    }

    // 如果都没找到，返回原始文件名
    console.warn(`未找到文件，返回原始文件名: ${safeOriginalName}`);
    return res.json({
      code: 200,
      message: '使用原始文件名',
      data: { filename: safeOriginalName }
    });

  } catch (error) {
    console.error('获取最终文件名失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取最终文件名失败: ' + error.message
    });
  }
});

// 上传分片接口
router.post('/upload/chunk', upload.single('chunk'), async (req, res) => {
  try {
    const originalName = decodeURIComponent(req.query.originalName);
    const chunkIndex = req.query.chunkIndex;
    const totalChunks = req.query.totalChunks;
    const fileMimeType = req.file.mimetype; // 获取文件 MIME 类型
    const fileId = req.query.fileId ? decodeURIComponent(req.query.fileId) : null;

    if (!originalName || chunkIndex === undefined || totalChunks === undefined) {
      console.error("缺少必要的分片信息 (来自请求参数)");
      return res.status(400).json({
        code: 400,
        message: '缺少必要的分片信息 (originalName, chunkIndex, totalChunks)'
      });
    }

    if (!req.file) {
      console.error("没有收到文件分片");
      return res.status(400).json({
        code: 400,
        message: '没有收到文件分片'
      });
    }

    // 确保文件名安全，移除可能导致路径问题的字符
    const safeOriginalName = originalName.replace(/[\/:*?"<>|]/g, '_');
    const currentChunkIndex = parseInt(chunkIndex);
    const totalExpectedChunks = parseInt(totalChunks);

    // 检查分片文件是否真的保存到了磁盘
    const expectedChunkPath = path.join(uploadBaseDir, `${safeOriginalName}_${currentChunkIndex}`);
    const actualChunkPath = req.file.path;

    console.log('文件路径检查:', {
      expected: expectedChunkPath,
      actual: actualChunkPath,
      exists: require('fs').existsSync(actualChunkPath)
    });

    if (!require('fs').existsSync(actualChunkPath)) {
      console.error(`分片文件保存失败: ${actualChunkPath}`);
      return res.status(500).json({
        code: 500,
        message: '分片文件保存失败'
      });
    }

    // 如果是最后一个分片，开始合并并处理文件
    if (currentChunkIndex === totalExpectedChunks - 1) {
      console.log(`处理最后一个分片：${safeOriginalName}, 共 ${totalExpectedChunks} 个分片`);

      try {
        // 强制垃圾回收（如果可用）
        if (global.gc) {
          global.gc();
          console.log('执行垃圾回收');
        }

        const mergedFilePath = await mergeChunks(safeOriginalName, totalExpectedChunks);
        console.log(`合并完成，文件路径: ${mergedFilePath}`);

        // 检查合并后的文件
        const mergedStats = await fsPromises.stat(mergedFilePath);
        console.log(`合并文件大小: ${Math.round(mergedStats.size / 1024 / 1024 * 100) / 100} MB`);

        // 调用新的 processFile 函数，根据文件类型进行处理
        const processedFileName = await processFile(mergedFilePath, safeOriginalName, fileMimeType);
        console.log(`文件处理完成，文件名: ${processedFileName}`);

        // 合并后内存状态
        const memUsageAfter = process.memoryUsage();
        res.json({
          code: 200,
          message: '文件上传完成',
          data: { filename: processedFileName }
        });

      } catch (mergeError) {
        console.error('合并分片失败详细信息:', {
          error: mergeError.message,
          stack: mergeError.stack,
          filename: safeOriginalName,
          totalChunks: totalExpectedChunks,
          mimeType: fileMimeType,
          timestamp: new Date().toISOString(),
          memoryUsage: process.memoryUsage()
        });

        // 尝试清理可能残留的分片文件
        try {
          for (let i = 0; i < totalExpectedChunks; i++) {
            const chunkPath = path.join(uploadBaseDir, `${safeOriginalName}_${i}`);
            try {
              await fsPromises.unlink(chunkPath);
              console.log(`清理残留分片: ${chunkPath}`);
            } catch (cleanupErr) {
              // 忽略清理错误
            }
          }
        } catch (cleanupError) {
          console.warn('清理残留分片失败:', cleanupError.message);
        }

        return res.status(500).json({
          code: 500,
          message: '合并分片失败: ' + mergeError.message,
          details: {
            filename: safeOriginalName,
            totalChunks: totalExpectedChunks,
            error: mergeError.message
          }
        });
      }
    } else {
      res.json({
        code: 200,
        message: '分片上传成功',
        data: { chunkIndex: currentChunkIndex }
      });
    }
  } catch (error) {
    console.error('分片上传接口内部错误 (500 Internal Server Error):', error.stack || error.message || error);
    res.status(500).json({
      code: 500,
      message: '上传失败: ' + (error.message || '未知错误')
    });
  } finally {
    console.log("-------------------------------------------------------");
  }
});

// 获取社区帖子列表
router.get('/posts', async (req, res) => {
  try {
    const { page = 1, limit = 10, sortBy } = req.query;

    let sortOption = { createdAt: -1 }; // 默认按创建时间降序

    // 根据 sortBy 参数设置排序选项
    if (sortBy === 'likes') {
      sortOption = { likes: -1, createdAt: -1 }; // 按点赞数降序，点赞数相同则按创建时间降序
    }
    // 可以根据需要添加其他排序规则，例如 comments, favorites
    const [posts, total] = await Promise.all([
      postModel.find()
        .sort(sortOption) // 使用新的排序选项
        .skip((page - 1) * limit)
        .limit(parseInt(limit)),
      postModel.countDocuments()
    ]);

    // 格式化返回数据
    const formattedPosts = posts.map(post => {
      const createdTime = new Date(post.createdAt);
      const now = new Date();
      const diffMs = now - createdTime;
      const diffMins = Math.floor(diffMs / 60000);
      const diffHours = Math.floor(diffMins / 60);
      const diffDays = Math.floor(diffHours / 24);

      let timeStr = '';
      if (diffDays > 0) {
        timeStr = `${diffDays}天前`;
      } else if (diffHours > 0) {
        timeStr = `${diffHours}小时前`;
      } else if (diffMins > 0) {
        timeStr = `${diffMins}分钟前`;
      } else {
        timeStr = '刚刚';
      }

      return {
        id: post._id,
        username: post.username,
        avatar: post.avatar,
        time: timeStr,
        content: post.content,
        images: post.images,
        stats: {
          likes: post.likes,
          comments: post.comments,
          favorites: post.favorites
        },
        isFollowing: false // 默认未关注，实际应从用户关系表查询
      };
    });

    res.json({
      code: 200,
      message: '获取成功',
      data: {
        list: formattedPosts,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});


// 发布社区帖子
router.post('/posts', async (req, res) => {
  try {
    const { content, imageNames = [] } = req.body;

    // 验证内容
    if (!content || content.trim().length === 0) {
      throw new Error('内容不能为空');
    }
    if (content.length > 500) {
      throw new Error('内容长度不能超过500字');
    }

    // 随机用户名和头像
    const avatars = [
      '/use1.jpg',
      '/use2.jpg',
      '/use3.jpg',
      '/use4.jpg',
      '/use5.jpg',
      '/use6.jpg',
      '/use7.jpg',
    ];
    const randomAvatar = avatars[Math.floor(Math.random() * avatars.length)];
    const randomUsername = `用户_${Math.floor(Math.random() * 10000)}`;

    // 创建新帖子
    const newPost = new postModel({
      username: randomUsername,
      avatar: randomAvatar,
      content,
      images: imageNames.map(name => `/uploads/${name}`),
      createdAt: new Date()
    });

    await newPost.save();

    // 格式化返回数据
    const formattedPost = {
      id: newPost._id,
      username: newPost.username,
      avatar: newPost.avatar,
      time: '刚刚',
      content: newPost.content,
      images: newPost.images,
      stats: {
        likes: 0,
        comments: 0,
        favorites: 0
      },
      isFollowing: false
    };

    res.status(201).json({
      code: 201,
      message: '发布成功',
      data: formattedPost
    });
  } catch (error) {
    console.error('发布错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 逛集市首页数据渲染
// 新增：处理点赞/取消点赞接口
router.post('/posts/:id/like', async (req, res) => {
  try {
    const postId = req.params.id;
    const { action } = req.body; // action 可以是 'like' 或 'unlike'

    if (!mongoose.Types.ObjectId.isValid(postId)) {
      return res.status(400).json({ code: 400, message: '无效的帖子ID' });
    }

    const post = await postModel.findById(postId);
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子未找到' });
    }

    if (action === 'like') {
      post.likes += 1;
      await post.save();
      res.json({ code: 200, message: '点赞成功', data: { likes: post.likes } });
    } else if (action === 'unlike') {
      if (post.likes > 0) {
        post.likes -= 1;
        await post.save();
      }
      res.json({ code: 200, message: '取消点赞成功', data: { likes: post.likes } });
    } else {
      return res.status(400).json({ code: 400, message: '无效的操作' });
    }

  } catch (error) {
    console.error('点赞/取消点赞失败:', error);
    res.status(500).json({ code: 500, message: '服务器错误: ' + error.message });
  }
});

// 新增：处理收藏/取消收藏接口
router.post('/posts/:id/favorite', async (req, res) => {
  try {
    const postId = req.params.id;
    const { action } = req.body; // action 可以是 'favorite' 或 'unfavorite'

    if (!mongoose.Types.ObjectId.isValid(postId)) {
      return res.status(400).json({ code: 400, message: '无效的帖子ID' });
    }

    const post = await postModel.findById(postId);
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子未找到' });
    }

    if (action === 'favorite') {
      post.favorites += 1;
      await post.save();
      res.json({ code: 200, message: '收藏成功', data: { favorites: post.favorites } });
    } else if (action === 'unfavorite') {
      if (post.favorites > 0) {
        post.favorites -= 1;
        await post.save();
      }
      res.json({ code: 200, message: '取消收藏成功', data: { favorites: post.favorites } });
    } else {
      return res.status(400).json({ code: 400, message: '无效的操作' });
    }

  } catch (error) {
    console.error('收藏/取消收藏失败:', error);
    res.status(500).json({ code: 500, message: '服务器错误: ' + error.message });
  }
});

// 新增：处理评论接口 (更新为保存评论内容)
router.post('/posts/:id/comment', async (req, res) => {
  try {
    const postId = req.params.id;
    const { commentContent, username, avatar, location } = req.body; // 接收评论内容、用户名、头像和位置

    if (!mongoose.Types.ObjectId.isValid(postId)) {
      return res.status(400).json({ code: 400, message: '无效的帖子ID' });
    }
    if (!commentContent || commentContent.trim().length === 0) {
      return res.status(400).json({ code: 400, message: '评论内容不能为空' });
    }

    const post = await postModel.findById(postId);
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子未找到' });
    }

    // 随机用户名和头像 (这里简化处理，实际应从用户认证获取)
    const avatars = [
      '/use1.jpg', '/use2.jpg', '/use3.jpg', '/use4.jpg',
      '/use5.jpg', '/use6.jpg', '/use7.jpg',
    ];
    const randomAvatar = avatar || avatars[Math.floor(Math.random() * avatars.length)];
    const randomUsername = username || `用户_${Math.floor(Math.random() * 10000)}`;
    const randomLocation = location || '未知地点';

    const newComment = {
      username: randomUsername,
      avatar: randomAvatar,
      content: commentContent,
      createdAt: new Date(),
      likes: 0, // 新评论点赞数默认为0
      location: randomLocation
    };

    post.commentDetails.push(newComment); // 将新评论添加到评论数组
    post.comments += 1; // 评论总数加1

    await post.save();

    res.json({
      code: 200,
      message: '评论成功',
      data: {
        comments: post.comments,
        newComment: newComment // 返回新评论，前端可以立即显示
      }
    });

  } catch (error) {
    console.error('评论失败:', error);
    res.status(500).json({ code: 500, message: '服务器错误: ' + error.message });
  }
});

// 新增：获取帖子评论列表接口
router.get('/posts/:id/comments', async (req, res) => {
  try {
    const postId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(postId)) {
      return res.status(400).json({ code: 400, message: '无效的帖子ID' });
    }

    const post = await postModel.findById(postId).select('commentDetails comments'); // 只查询评论详情和评论总数
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子未找到' });
    }

    // 对评论进行时间格式化（与帖子时间格式化类似）
    const formattedComments = post.commentDetails.map(comment => {
      const createdTime = new Date(comment.createdAt);
      const now = new Date();
      const diffMs = now - createdTime;
      const diffMins = Math.floor(diffMs / 60000);
      const diffHours = Math.floor(diffMins / 60);
      const diffDays = Math.floor(diffHours / 24);

      let timeStr = '';
      if (diffDays > 0) {
        timeStr = `${diffDays}天前`;
      } else if (diffHours > 0) {
        timeStr = `${diffHours}小时前`;
      } else if (diffMins > 0) {
        timeStr = `${diffMins}分钟前`;
      } else {
        timeStr = '刚刚';
      }

      return {
        id: comment._id, // 评论的ID
        username: comment.username,
        avatar: comment.avatar,
        content: comment.content,
        time: timeStr,
        likes: comment.likes,
        location: comment.location
      };
    }).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)); // 按时间降序排列评论

    res.json({
      code: 200,
      message: '获取评论成功',
      data: {
        totalComments: post.comments,
        comments: formattedComments
      }
    });

  } catch (error) {
    console.error('获取评论失败:', error);
    res.status(500).json({ code: 500, message: '服务器错误: ' + error.message });
  }
});

// 新增：处理评论点赞/取消点赞接口
router.post('/posts/:postId/comments/:commentId/like', async (req, res) => {
  try {
    const { postId, commentId } = req.params;
    const { action } = req.body; // 'like' or 'unlike'

    if (!mongoose.Types.ObjectId.isValid(postId) || !mongoose.Types.ObjectId.isValid(commentId)) {
      return res.status(400).json({ code: 400, message: '无效的ID格式' });
    }

    const post = await postModel.findById(postId);
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子未找到' });
    }

    const comment = post.commentDetails.id(commentId);
    if (!comment) {
      return res.status(404).json({ code: 404, message: '评论未找到' });
    }

    if (action === 'like') {
      comment.likes += 1;
    } else if (action === 'unlike') {
      if (comment.likes > 0) {
        comment.likes -= 1;
      }
    } else {
      return res.status(400).json({ code: 400, message: '无效的操作' });
    }

    await post.save(); // 保存整个帖子文档

    res.json({
      code: 200,
      message: `${action === 'like' ? '点赞' : '取消点赞'}评论成功`,
      data: { likes: comment.likes }
    });

  } catch (error) {
    console.error('评论点赞/取消点赞失败:', error);
    res.status(500).json({ code: 500, message: '服务器错误: ' + error.message });
  }
});

// 添加评论回复接口
router.post('/posts/:postId/comments/:commentId/reply', async (req, res) => {
  try {
    const { postId, commentId } = req.params;
    const { content } = req.body;

    // 验证参数
    if (!content || !content.trim()) {
      return res.status(400).json({
        code: 400,
        message: '回复内容不能为空'
      });
    }

    // 查找对应的帖子和评论
    const post = await postModel.findById(postId);
    if (!post) {
      return res.status(404).json({
        code: 404,
        message: '帖子不存在'
      });
    }

    // 找到对应的评论
    const comment = post.commentDetails.id(commentId);
    if (!comment) {
      return res.status(404).json({
        code: 404,
        message: '评论不存在'
      });
    }

    // 创建新回复对象
    const newReply = {
      content: content.trim(),
      username: '用户_' + Math.floor(Math.random() * 1000),
      avatar: '/default-avatar.png',
      createdAt: new Date(),
      likes: 0
    };

    // 初始化评论的replies数组（如果不存在）
    if (!comment.replies) {
      comment.replies = [];
    }

    // 添加回复到评论中
    comment.replies.push(newReply);

    // 更新回复数量
    comment.replyCount = (comment.replyCount || 0) + 1;

    // 保存更新后的帖子
    await post.save();

    // 返回新回复
    res.status(200).json({
      code: 200,
      message: '回复成功',
      data: {
        ...newReply,
        commentId: commentId,
        _id: comment.replies[comment.replies.length - 1]._id
      }
    });

  } catch (error) {
    console.error('添加回复失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误'
    });
  }
});

// 修改：获取帖子评论列表接口，包含回复
router.get('/posts/:id/comments', async (req, res) => {
  try {
    const postId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(postId)) {
      return res.status(400).json({ code: 400, message: '无效的帖子ID' });
    }

    const post = await postModel.findById(postId).select('commentDetails comments');
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子未找到' });
    }

    // 格式化评论及其回复
    const formattedComments = post.commentDetails.map(comment => {
      const createdTime = new Date(comment.createdAt);
      const now = new Date();
      const diffMs = now - createdTime;
      const diffMins = Math.floor(diffMs / 60000);
      const diffHours = Math.floor(diffMins / 60);
      const diffDays = Math.floor(diffHours / 24);

      let timeStr = '';
      if (diffDays > 0) {
        timeStr = `${diffDays}天前`;
      } else if (diffHours > 0) {
        timeStr = `${diffHours}小时前`;
      } else if (diffMins > 0) {
        timeStr = `${diffMins}分钟前`;
      } else {
        timeStr = '刚刚';
      }

      // 格式化回复
      const formattedReplies = comment.replies.map(reply => {
        const replyCreatedTime = new Date(reply.createdAt);
        const replyDiffMs = now - replyCreatedTime;
        const replyDiffMins = Math.floor(replyDiffMs / 60000);
        const replyDiffHours = Math.floor(replyDiffMins / 60);
        const replyDiffDays = Math.floor(replyDiffHours / 24);

        let replyTimeStr = '';
        if (replyDiffDays > 0) {
          replyTimeStr = `${replyDiffDays}天前`;
        } else if (replyDiffHours > 0) {
          replyTimeStr = `${replyDiffHours}小时前`;
        } else if (replyDiffMins > 0) {
          replyTimeStr = `${replyDiffMins}分钟前`;
        } else {
          replyTimeStr = '刚刚';
        }

        return {
          id: reply._id,
          username: reply.username,
          avatar: reply.avatar,
          content: reply.content,
          time: replyTimeStr,
          likes: reply.likes
        };
      }).sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt)); // 回复按时间升序

      return {
        id: comment._id,
        username: comment.username,
        avatar: comment.avatar,
        content: comment.content,
        time: timeStr,
        likes: comment.likes,
        location: comment.location,
        replies: formattedReplies // 包含格式化后的回复
      };
    }).sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)); // 评论按时间降序排列

    res.json({
      code: 200,
      message: '获取评论成功',
      data: {
        totalComments: post.comments,
        comments: formattedComments
      }
    });

  } catch (error) {
    console.error('获取评论失败:', error);
    res.status(500).json({ code: 500, message: '服务器错误: ' + error.message });
  }
});


// 集市商品展示

// 刘家兴
router.get('/shifta', async (req, res) => {
  try {
    const shishous = await shishouModel.find().sort({ _id: -1 });
    res.json({  // 改为返回JSON
      code: 200,
      message: '获取成功',
      data: shishous
    });
  } catch (error) {
    console.error('集市首页渲染错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误，请稍后重试',
      error: error.message
    });
  }
});

// 评论数据展示
router.get('/ping', async (req, res) => {
  try {
    const pingjias = await pingjiaModel.find().sort({ _id: -1 });

    console.log('pingjias:', pingjias);
    res.json({  // 改为返回JSON
      code: 200,
      message: '获取成功',
      data: pingjias
    });
  } catch (error) {
    console.error('评论渲染错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误，请稍后重试',
      error: error.message
    });
  }
});

// 集市商品数据搜索
router.get('/shifta/search', async (req, res) => {   // 改为GET请求
  try {
    const { keyword } = req.query;
    const shishous = await shishouModel.find({ name: new RegExp(keyword, 'i') }).sort({ _id: -1 });
    res.json({  // 改为返回JSON
      code: 200,
      message: '搜索成功',
      data: shishous
    });
  } catch (error) {
    console.error('集市详情页搜索错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误，请稍后重试',
      error: error.message
    });
  }
});

// 点赞接口

router.post('/ping/like', async (req, res) => {
  try {
    const { id } = req.body; // 获取评价ID
    
    // 查找评价
    const review = await pingjiaModel.findById(id);
    if (!review) {
      return res.status(404).json({
        code: 404,
        message: '评价不存在'
      });
    }
    
    // 点赞数+1
    review.zan += 1;
    await review.save();
    
    res.json({
      code: 200,
      message: '点赞成功',
      data: {
        likes: review.zan
      }
    });
  } catch (error) {
    console.error('点赞失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});


//引入sdk包
let AlipaySdk = require("alipay-sdk").default
let AlipaySdkFormData = require("alipay-sdk/lib/form").default

router.post('/alipay', async function (req, res) {
  // 实例化商家信息 把网站付款的钱付给哪个商家
  let { outTradeNo, subject, totalAmount } = req.body


  const alipaySdk = new AlipaySdk({
    // 设置应用 ID
    appId: '9021000122690421',
    // 设置应用私钥
    privateKey: "MIIEowIBAAKCAQEAy4z4UKAKZaCe+NtCaHYrq+rvrM73hZlo9uVytf90R/XlBFOlIYpMHBrEwgvZwJIcbqMJnAbqbVQt8Do6UzK1Az/HdM93qpegLOF9WtValdmLhqPVo3nL0ZmO3xDoGgEsrm/5FF77jpuNz9X6mM27fafR8KgpJz3lFT13ORNynZeL94RdUvKyVGrTaTIqYpvMDnLR3wFwnKExZ384HSTUYWesnKHFYQsEA/8UjLdU1HGNtkhpgxFemo9zfWJelFWi6npBlhlLyRbc611x860MzkSHVlDWqM/i97auJfq6vWT2g4BZIk42q7cZKizEOJI9PU76hKRQ1FyYZCYkXR20PwIDAQABAoIBAFsgdVrDC2SMEB+hKY3SuaJxv3NCBRZOo+tEtaI9BzXgI/NX7ymg3IoIgeXNoGLSBuCRJRAxGGpxsU9HAi2VGeymdQkaiJxa3V66ZIBx2+gSSKCyYEablF/1uzyqOP7LX9GIV56DF2O0yDwvs80M7c9HfnmbDzF+SDzGE8X9quZZ0cM9ezO8HGR9eDCLR/tY4g40ynTefgOXftrqyim9KFPeumw5t9Ewm85LtgQRChDEZnVhmU6HUx4OcUIXjiJbwb0Svi80+IWZJTq0FKl29Cu1OcV3CnB9RydAfUpga1WmbLlTJmM+5Hhd8Wk7pPZ+45jYm/7j3mzhR+/g8W05yKECgYEA7c6WqxpA/ZWsTzNodHU6+XF34seD1pb83OJI1rSljmZRO8wk5mymGWBFzNy6GBFu6KNxSwTrdVStl9WVtyPG7bGpzAyLnbmVf7fN9X8f5z3HrSBKxjFybHskRA0+1nWi1djX8UiaLNGIkYzXh7SvnstetKs6qkyXlE+ES5l6QcsCgYEA2x96FQ0J71+xLaM+GfdIWEH30mxlmXIIIEmEYArc//XKecsKvmbC92xFIFIl8spaW7Ig8k6JkxcIAs9V2ToYW3Lrp1MCotW6t4bknZkPspyWErFJmVFcNaK41fxqCJgnvTNU9aIGVoBuCMp8YFcJ3U3rNHAd+St1ZjZoqtC7uN0CgYEA4HM8ggIllTLPj3FWBZUgNI+EN+dX6BJaV6C8Xunh2KV5xpbHvTSPESRsvQ8YFd9ebvTU2ZmrIvLpZYWR6Wk7ON2XBaBRpmyjTgiNvEhgNEF7VUxFRwsklH8lm5Vk2cXuCyi/qFx+KA8cd0QXqV5A4//PQ3bZyCLCbpkepLwXSEECgYBctj/AQmkOuA1OQwCWmfMpLJg/lw+R0hawGosA2/fP8N4/k/Iyx2X8q/m/iCJ4TLfYjlC0VRiOfLMuBS3MoHEH2GLuxAecgBPlbRSzvbxPlUNGG28JiMwcAYJ1P7xZcI931Q1AdNJ7rRFhdNMVLB6HXV2ELV/xOjsNCT5V78VNnQKBgFI/c4RcQP6bGo9CMCMoKJ2MLkpSF13Pq+J/T62ymCgnuq2HvoR2qBeYxAiTTlNE7CWyAXUhDRGRjgbv3v7ZVC6FupUyHiNn8XnKPPfjfo9PPA09a2ZOn9NjxazQbCHdmDm4Kz/OmDBc4DkTt429CEok27tfF6CsPTRIbp3JTCZ2",
    // 设置支付宝公钥
    alipayPublicKey: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuyjBD9/4koTB92uXDd+AnBn0fh5l7VrRlpTZio1UEZiE3gkwTTqYcf5atL8cdR1Un8Zn8sh/RMWKOAd7nHSDmlP4IxW6cvrxcDXb4KKxgmcgAlAyq27Egk+wwT5QS+v/s+esXm4GwBFs6dWczrSxFUp+PVKXMkhF4N/PHO8X8u/GbRjRdEJC7S0SpLVEYhIo//9/sI50bOrlmxSdKPXMbDN7EQT6fcEIrJgjxNyEsoamS4IHKcRWtPbRsXuM+btnpnjmkyMXeztg/NuBn4Bl46gpHuvtFWlNbZlKabyFCEnrIbMlI7RfcM1nOGUDPTgOulgESlkn7Z8cK0xFO7FvJQIDAQAB",
    // 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
    // keyType: 'PKCS1',
    // 设置网关地址，默认是 https://openapi.alipay.com
    // endpoint: 'https://openapi.alipay.com',
    "gateway": "https://openapi-sandbox.dl.alipaydev.com/gateway.do"
  })

  //   支付商品信息
  const formData = new AlipaySdkFormData();
  formData.addField("bizContent", {
    // 一个订单只能支付一次
    out_trade_no: outTradeNo,
    product_code: "FAST_INSTANT_TRADE_PAY",  // 支付信息的订单编号 前端在确定订单的时候会生产订单信息 包括订单编号
    subject: subject, // 商品名称
    body: "234",
    total_amount: totalAmount  // 支付金额
  })

  // 第三方接口 实现支付功能


  // 支付成功后跳转到前端的一个路由
  formData.addField("returnUrl", "http://localhost:5173/xiyou")

  // 支付有PC端和移动端 
  //   alipay.trade.page.pay PC端
  // alipay.trade.wap.pay 移动端
  let result = await alipaySdk.exec("alipay.trade.wap.pay", {}, {
    formData: formData
  })
  console.log(result, 123123);
  res.send(result)

})


// 王舒畅
router.get('/news', async (req, res) => {
  const data = await newsModel.find()
  res.json({  // 改为返回JSON
    code: 200,
    message: '获取成功',
    data: data
  });
})
router.post('/adds', async function (req, res) {
  await newsModel.create(req.body)
  res.json({
    code: 200
  })
})
router.post('/edits', async function (req, res) {
  await newsModel.updateOne({ _id: req.body._id }, req.body)
  res.json({
    code: 200
  })
})

router.post('/deletes', async function (req, res) {
  await newsModel.deleteOne({ _id: req.body._id })
  res.json({
    code: 200
  })
})
// 详情
router.get('/detail/:id', async function (req, res) {
  const { id } = req.params
  const data = await newsModel.findById(id)
  res.json({
    code: 200,
    data: data
  })
})

const storage1 = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, uniqueSuffix + path.extname(file.originalname))
  }
})

const uploads1 = multer({ storage: storage1 })

router.post('/uploads', uploads1.single('img'), function (req, res) {
  if (!req.file) {
    return res.json({
      code: 400,
      message: '请选择要上传的图片'
    })
  }
  res.json({
    code: 200,
    message: '上传成功',
    data: `http://localhost:3000/uploads/${req.file.filename}`
  })
})

// 非遗知识问答API接口

// 获取随机题目
router.get('/quiz/random', async (req, res) => {
  try {
    const count = parseInt(req.query.count) || 5; // 默认返回5个题目
    
    // 使用aggregate实现真正随机
    const randomQuizzes = await quizModel.aggregate([
      { $sample: { size: count } }
    ]);
    
    if (randomQuizzes.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '没有找到题目',
        data: null
      });
    }
    
    res.json({
      code: 200,
      message: '获取成功',
      data: randomQuizzes
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 提交答案并获取结果
router.post('/quiz/submit', async (req, res) => {
  try {
    const { userId, answers, timeSpent } = req.body;
    
    if (!userId || !answers || !Array.isArray(answers)) {
      return res.status(400).json({
        code: 400,
        message: '参数错误',
        data: null
      });
    }
    
    // 获取题目信息
    const questionIds = answers.map(item => item.questionId);
    const questions = await quizModel.find({ _id: { $in: questionIds } });
    
    // 计算得分和结果
    let correctCount = 0;
    const results = [];
    const userAnswers = [];
    const correctAnswers = [];
    
    for (let i = 0; i < answers.length; i++) {
      const userAnswer = answers[i].answer;
      const question = questions.find(q => q._id.toString() === answers[i].questionId);
      
      if (question) {
        const isCorrect = userAnswer === question.correctAnswer;
        if (isCorrect) correctCount++;
        
        results.push({
          question: question.question,
          options: question.options,
          userAnswer,
          correctAnswer: question.correctAnswer,
          isCorrect,
          explanation: question.explanation
        });
        
        userAnswers.push(userAnswer);
        correctAnswers.push(question.correctAnswer);
      }
    }
    
    const score = Math.round((correctCount / answers.length) * 10); // 满分10分
    
    // 保存答题记录
    const quizRecord = new quizRecordModel({
      userId,
      quizIds: questionIds,
      userAnswers,
      correctAnswers,
      score,
      totalQuestions: answers.length,
      timeSpent: timeSpent || 0
    });
    
    await quizRecord.save();
    
    res.json({
      code: 200,
      message: '提交成功',
      data: {
        score,
        correctCount,
        totalQuestions: answers.length,
        timeSpent: timeSpent || 0,
        results
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 获取单题详情
router.get('/quiz/:id', async (req, res) => {
  try {
    if (!mongoose.Types.ObjectId.isValid(req.params.id)) {
      return res.status(400).json({
        code: 400,
        message: '无效的ID格式',
        data: null
      });
    }
    
    const quiz = await quizModel.findById(req.params.id);
    if (!quiz) {
      return res.status(404).json({
        code: 404,
        message: '题目不存在',
        data: null
      });
    }
    
    res.json({
      code: 200,
      message: '获取成功',
      data: quiz
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 获取用户答题历史
router.get('/quiz/history/:userId', async (req, res) => {
  try {
    const { userId } = req.params;
    const { page = 1, limit = 10 } = req.query;
    
    const [records, total] = await Promise.all([
      quizRecordModel.find({ userId })
        .sort({ completedAt: -1 })
        .skip((page - 1) * limit)
        .limit(parseInt(limit)),
      quizRecordModel.countDocuments({ userId })
    ]);
    
    res.json({
      code: 200,
      message: '获取成功',
      data: {
        list: records,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 添加题目（管理员功能）
router.post('/quiz', async (req, res) => {
  try {
    const { title, question, options, correctAnswer, explanation, category, difficulty } = req.body;
    
    if (!question || !options || !correctAnswer || !explanation) {
      return res.status(400).json({
        code: 400,
        message: '必填字段不能为空',
        data: null
      });
    }
    
    const quiz = new quizModel({
      title: title || question.substring(0, 20) + '...',
      question,
      options,
      correctAnswer,
      explanation,
      category: category || '非遗知识',
      difficulty: difficulty || 1
    });
    
    await quiz.save();
    
    res.json({
      code: 200,
      message: '添加成功',
      data: quiz
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// ==================== 本草纲目问答相关接口 ====================

// 获取本草纲目随机题目接口
router.get('/bencao-quiz/random', async (req, res) => {
  try {
    const count = parseInt(req.query.count) || 5; // 默认5题
    
    // 随机获取题目
    const questions = await bencaoQuizModel.aggregate([
      { $sample: { size: count } }
    ]);
    
    if (questions.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '暂无本草纲目题目',
        data: null
      });
    }
    
    // 移除正确答案和解析，只返回题目和选项
    const questionsForUser = questions.map(q => ({
      _id: q._id,
      title: q.title,
      question: q.question,
      options: q.options,
      category: q.category,
      difficulty: q.difficulty
    }));
    
    res.json({
      code: 200,
      message: '获取本草纲目题目成功',
      data: questionsForUser
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 提交本草纲目答案并获取结果
router.post('/bencao-quiz/submit', async (req, res) => {
  try {
    const { userId, answers, timeSpent } = req.body;
    
    if (!answers || !Array.isArray(answers)) {
      return res.status(400).json({
        code: 400,
        message: '答案格式错误',
        data: null
      });
    }
    
    // 获取题目详情
    const questionIds = answers.map(a => a.questionId);
    const questions = await bencaoQuizModel.find({ _id: { $in: questionIds } });
    
    // 计算得分
    let correctCount = 0;
    const results = [];
    const userAnswers = [];
    const correctAnswers = [];
    
    for (let i = 0; i < answers.length; i++) {
      const userAnswer = answers[i];
      const question = questions.find(q => q._id.toString() === userAnswer.questionId);
      
      if (question) {
        const isCorrect = userAnswer.answer === question.correctAnswer;
        if (isCorrect) correctCount++;
        
        userAnswers.push(userAnswer.answer);
        correctAnswers.push(question.correctAnswer);
        
        results.push({
          questionId: question._id,
          question: question.question,
          options: question.options,
          userAnswer: userAnswer.answer,
          correctAnswer: question.correctAnswer,
          isCorrect,
          explanation: question.explanation
        });
      }
    }
    
    const score = Math.round((correctCount / answers.length) * 10); // 10分制
    
    // 保存答题记录
    const record = new bencaoQuizRecordModel({
      userId: userId || 'anonymous',
      quizIds: questionIds,
      userAnswers,
      correctAnswers,
      score,
      totalQuestions: answers.length,
      timeSpent: timeSpent || 0
    });
    
    await record.save();
    
    res.json({
      code: 200,
      message: '本草纲目答题提交成功',
      data: {
        score,
        correctCount,
        totalQuestions: answers.length,
        timeSpent,
        results
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 获取本草纲目单题详情（用于查看解析）
router.get('/bencao-quiz/:id', async (req, res) => {
  try {
    const question = await bencaoQuizModel.findById(req.params.id);
    
    if (!question) {
      return res.status(404).json({
        code: 404,
        message: '本草纲目题目不存在',
        data: null
      });
    }
    
    res.json({
      code: 200,
      message: '获取成功',
      data: question
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 获取本草纲目用户答题历史
router.get('/bencao-quiz/history/:userId', async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    
    const [records, total] = await Promise.all([
      bencaoQuizRecordModel.find({ userId: req.params.userId })
        .sort({ completedAt: -1 })
        .skip((page - 1) * limit)
        .limit(parseInt(limit)),
      bencaoQuizRecordModel.countDocuments({ userId: req.params.userId })
    ]);
    
    res.json({
      code: 200,
      message: '获取本草纲目答题历史成功',
      data: {
        list: records,
        pagination: {
          total,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

// 添加本草纲目题目（管理员功能）
router.post('/bencao-quiz/add', async (req, res) => {
  try {
    const { title, question, options, correctAnswer, explanation, difficulty } = req.body;
    
    if (!title || !question || !options || !correctAnswer || !explanation) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要字段',
        data: null
      });
    }
    
    const quiz = new bencaoQuizModel({
      title,
      question,
      options,
      correctAnswer,
      explanation,
      difficulty: difficulty || 1
    });
    
    await quiz.save();
    
    res.json({
      code: 200,
      message: '本草纲目题目添加成功',
      data: quiz
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '服务器错误: ' + error.message,
      data: null
    });
  }
});

module.exports = { router, setupWebSocket };
 